/*
* 判断是否登录
* 公用配置/方法
* */

import Vue from 'vue'
import router from '../router'
import URL from './baseUrl'
import axios from 'axios'
import bus from '../components/common/bus'

// import COS from 'cos-nodejs-sdk-v5'
// 引入模块
// import {COS} from 'cos-nodejs-sdk-v5'
// const COS = require('cos-nodejs-sdk-v5');
// 创建实例
// const cos = new COS({
//     AppId: '1250000000',
//     SecretId: 'AKIDxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
//     SecretKey: 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
// });
const Qs = require('qs');

axios.defaults.withCredentials = true;
const config = {
  pdata: {ws: {}},
  isLogin: () => {
    return new Promise((resolve, reject) => {
      axios(URL + '/admin/basic/getLoginInfo').then(res => {
        if (res.data.code === '0') {
          resolve(true);
        } else {
          reject(false);
        }
      })
    });
  },
  ossUrl: '', // 东良恒州
  toUrl: (obj) => {
    let str = '';
    for (let i in obj) {
      str += '&' + i + '=' + obj[i] || '';
    }
    str = str.substr(1);
    return str;
  },
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded',
    'token': sessionStorage.getItem('token')||'',
  },
  get: (url, obj) => {
      return axios({
          url:URL+url+'?'+config.toUrl(obj),
          method: 'get',
          // withCredentials: false,
          // headers:{
          //     'Content-Type':'application/json;charse=UTF-8'
          // },
          headers: config.headers,
      });
  },
  post: (url, obj) => {
        return axios({
            url:URL+url,
            method: 'post',
            data: Qs.stringify(obj),
            headers: config.headers,
        });
  },
    // 移动端请求
    mget: (url, obj) => {
        let token = localStorage.getItem('mtoken')||'';
        return axios({
            url:URL+url+'?'+config.toUrl(obj),
            method: 'get',
            withCredentials: false,
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
                'token': token,
            },
        });
    },
    mpost: (url, obj) => {
        let token = localStorage.getItem('mtoken')||'';
        return axios({
            url:URL+url,
            method: 'post',
            data: Qs.stringify(obj),
            withCredentials: false,
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
                'token': token,
            },
        });
    },
    // 解决表格导入问题
  inster: (url, obj) => {
        let inster = axios.create({
            baseURL:URL,
            timeout:1000,
            headers: {
                'Content-Type': 'multipart/form-data',
            },
        });
        return inster.post(url,obj);
  },
  // 处理错误信息
  handleError: (data) => {
    if (data.code == '0') {
      return data.message;
    } else if (data.code == '-2001'||data.code == '-2002') {
        router.push({path: '/login'});
        // 利用缓存重新登录
        // this.storageLogin();
    } else {
      return data.message;
    }
  },
  // 处理错误信息
  mobileError: (data) => {
    if (data.code == '0') {
        return data.message;
    } else if (data.code === '-2001'||data.code === '-2002') {
        router.push({path: '/mobile/resident'});
        // 利用缓存重新登录
        // this.storageLogin();
    } else if(data.code === '-1001'){
        router.push({path: '/mobile/address-add'});
        return data.message;
    } else {
        return data.message;
    }
  },
  // 手机号验证
  isMobile: (str) => {
    // return /^(13[0-9]|15[012356789]|18[0123456789]|17[0123456789]|14[57])[0-9]{8}$/.test(str);
      return /^1(3|4|5|7|8|9)\d{9}$/.test(str);
  },
  // 验证url
  isUrl: (str) => {
    return /((([A-Za-z]{3,9}:(?:\/\/)?)(?:[-;:&=\+\$,\w]+@)?[A-Za-z0-9.-]+(:[0-9]+)?|(?:ww‌​w.|[-;:&=\+\$,\w]+@)[A-Za-z0-9.-]+)((?:\/[\+~%\/.\w-_]*)?\??(?:[-\+=&;%@.\w_]*)#?‌​(?:[\w]*))?)/.test(str);
  },
  // 验证身份证号
  isPersonCard: (card) => {
    return /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/.test(card);
  },
  // 密码验证
  pwd1: (password) => {
    return /^(\w){6,16}$/.test(password);
  },
  // 字母数字和符号
  pwd16: (password) => {
    return /^(\w){1,16}$/.test(password);
  },
  pwd50: (password) => {
    return /^(\w){1,50}$/.test(password);
  },
  // 字母数字和符号
  pwd30: (password) => {
    return /^(\w){1,30}$/.test(password);
  },
  // 字母数字和符号
  pwd32: (password) => {
    return /^(\w){1,32}$/.test(password);
  },
  // 字母数字和符号
  pwd100: (password) => {
    return /^(\w){1,100}$/.test(password);
  },
  // 获取登录用户信息
  getLoginInfo(){
    this.get('/housinggestate/base/getLoginInfo', {}).then(res=>{
        if(res.data.code==='0'){
            config.globalInfo.user = res.data.admin;
            // this.wsConnect();
            bus.$emit('adminInfo', '');
        }
    })
  },
  // 储存微信授权的信息
  globalInfo: {
    "user": {
    },
  },
    // 按钮权限判断(返回true:按钮显示; 返回false:按钮不显示)
  btnShow(code) {
        if (!window.sessionStorage.getItem('menuBtnArr')) {
            // location.reload();
        }
        let btnArr = JSON.parse(window.sessionStorage.getItem('menuBtnArr'));
        if (btnArr.indexOf(code) == -1) {
            return false;
        } else {
            return true;
        }
  },
    // 机器发声
  sayIt(query, language) {
        // let q = new SpeechSynthesisUtterance(query);
        // q.lang = language;
        // q.rate = 1.2;
        // speechSynthesis.speak(q);
        let div = document.createElement('div');
        div.setAttribute('id','bdtts_div_id2');
        document.getElementsByTagName('body')[0].appendChild(div);

        let el = document.getElementById('bdtts_div_id2');
        let au1 = '<audio id="tts_autio_id" autoplay="autoplay">';
        let sss = '<source id="tts_source_id" src="http://tts.baidu.com/text2audio?lan=zh&ie=UTF-8&spd=6&text=' + query + '"type="audio/mpeg">';
        let eee = '<embed id="tts_embed_id" height="0" width="0" src="">';
        let au2 = '</audio>';
        el.innerHTML = au1 + sss + eee + au2;
        // el.src = 'http://tts.baidu.com/text2audio?lan=' + language + '&ie=UTF-8&text=' + query + '&spd=' + 5;
        setTimeout(s=>{
            document.getElementsByTagName('body')[0].removeChild(div);
        },4000);
  },
  // websocket链接
  wsConnect() {
    let info = this.globalInfo;
    if(!sessionStorage.getItem('websocketInfo')) return;
    let ws = new WebSocket('wss://chang2.xiao2yun.com/ws'+'?'+config.toUrl(JSON.parse(sessionStorage.getItem('websocketInfo'))));
    ws.onopen = (evt) => {
      this.onOpen(evt)
    };
    ws.onclose = (evt) => {
      this.onClose(evt)
    };
    ws.onmessage = (evt) => {
        // this.onMessage(evt.data);
      if (typeof evt.data !== 'string') {
        let reader = new FileReader();
        reader.onload = (eve) => {
          this.onMessage(JSON.parse(eve['target']['result']));
        };
        reader.readAsText(evt.data, 'utf-8');
      }
    };
    ws.onerror = (evt) => {
      this.onError(evt)
    };

    this.pdata.ws = ws;
  },
  // 微信jssdk配置config
  wxConfig(){
    let url = location.href.split('#')[0];
    axios.post(URL + '/qraftermeal/login/weixinConfig', config.toUrl({url: url})).then(res=>{
      if(res.data.code=='0'){
        let obj = res.data.map;
        wx.config({
          debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
          appId: obj.appid, // 必填，公众号的唯一标识
          timestamp: obj.timestamp, // 必填，生成签名的时间戳
          nonceStr: obj.noncestr, // 必填，生成签名的随机串
          signature: obj.sign,// 必填，签名
          jsApiList: [
            'checkJsApi',  //判断当前客户端版本是否支持指定JS接口
            'scanQRCode',
            'openLocation',
            'updateTimelineShareData',
            'onMenuShareTimeline', //分享给好友
            'onMenuShareAppMessage', //分享到朋友圈
            'onMenuShareQQ',  //分享到QQ
            'onMenuShareWeibo' //分享到微博<br/>
          ] // 必填，需要使用的JS接口列表
        });
      }
    }).catch();
  },
  onOpen(evt) {
      console.log('websocket连接成功',evt);
  },
  onClose(evt) {
      console.log('websocket连接关闭',evt);
      this.wsConnect();
  },
  onMessage(evt) {
      console.log(evt, 'websocket消息接收到了');
      bus.$emit('websocketMsg', evt);
  },
  onError(evt) {
  },
  getWs() {
    return this.pdata.ws;
  },

};
// config.wsConnect();
const vueMethod = {
};

export {config, vueMethod};
